<script setup>
import { computed, reactive, ref } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { cloneDeep } from 'lodash'
import dayjs from 'dayjs'
import vue3Cron from '@/components/vue3-cron/index.vue'
import { apiHome } from '@/api/healthAssessment'

const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})
const visible = ref(false)

const columns = [
  {
    title: '序号',
    slotName: 'index',
    width: 60
  },
  {
    title: '任务名称',
    dataIndex: 'taskName'
  },
  {
    title: '健康值分析',
    dataIndex: 'healthAnalysis'
  },
  {
    title: '健康得分',
    dataIndex: 'healthScore'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    render: ({ record }) => {
      if (record.createTime) {
        return dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')
      } else {
        return ''
      }
    },
    width: 175
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    render: ({ record }) => {
      if (record.startTime) {
        return dayjs(record.startTime).format('YYYY-MM-DD HH:mm:ss')
      } else {
        return ''
      }
    },
    width: 175
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    render: ({ record }) => {
      if (record.endTime) {
        return dayjs(record.endTime).format('YYYY-MM-DD HH:mm:ss')
      } else {
        return ''
      }
    },
    width: 175
  },
  {
    title: '操作',
    slotName: 'action',
    width: 305
  }
]
const scroll = {
  x: '100%',
  maxHeight: '700px'
}
const tableLoading = ref(false)
const taskPageData = ref([])

const dialogTitle = computed(() => {
  switch (dialogType.value) {
    case 'add':
      return '添加任务'
    case 'edit':
      return '修改任务信息'
    default:
      return ''
  }
})

const descData = ref([
  {
    label: '任务名称',
    code: 'taskName',
    value: ''
  },
  {
    label: '评估开始时间',
    code: 'startTime',
    value: ''
  },
  {
    label: '评估结束时间',
    code: 'endTime',
    value: ''
  },
  {
    label: '评估系统',
    code: 'indexSystemId',
    value: ''
  },
  {
    label: '健康评估分数',
    code: 'healthScore',
    value: ''
  },
  {
    label: '任务描述',
    code: 'taskDesc',
    value: ''
  },
  {
    label: '健康分析描述',
    code: 'healthAnalysis',
    value: ''
  },
  {
    label: 'Bean名称',
    code: 'beanName',
    value: ''
  },
  {
    label: '方法名称',
    code: 'methodName',
    value: ''
  },
  {
    label: '方法入参',
    code: 'methodParams',
    value: ''
  },
  {
    label: 'Cron表达式',
    code: 'cronExpression',
    value: ''
  },
  {
    label: '任务状态',
    code: 'taskStatus',
    value: ''
  },
  {
    label: '任务类型',
    code: 'taskType',
    value: ''
  },
  {
    label: '备注',
    code: 'remark',
    value: ''
  },
  {
    label: '更新时间',
    code: 'updateTime',
    value: ''
  },
  {
    label: '创建时间',
    code: 'createTime',
    value: ''
  }
])

const dialogType = ref('add')
const taskFormRef = ref()

const DEFAULT_TASK_FORM = {
  taskName: '',
  indexSystemId: '',
  cronExpression: '',
  dateRange: [],
  remark: '',
  startTime: '',
  endTime: ''
}

const taskFormRules = {
  taskName: [{ required: true, message: '请填写任务名称', trigger: ['change', 'input'] }],
  indexSystemId: [{ required: true, message: '请填写评估系统', trigger: ['change', 'input'] }],
  cronExpression: [{ required: true, message: '请填写或选择corn表达式', trigger: ['change', 'input'] }],
  dateRange: [{ required: true, message: '请选择查询数据时间段', trigger: ['change', 'input'] }]
}

const taskForm = ref(cloneDeep(DEFAULT_TASK_FORM))
const handleAdd = () => {
  dialogType.value = 'add'
  visible.value = true
  getSystemSelectList()
}

const handleSubmit = async () => {
  const API = dialogType.value === 'add' ? apiHome.createTaskAPI : apiHome.updateTaskAPI
  if (!taskFormRef.value) return false
  const res = await taskFormRef.value.validate()
  if (res !== undefined) return false
  try {
    const { code, data, message } = await API(taskForm.value)
    if (code === 200) {
      Message.success(message || data)
      await loadList()
      return true
    } else {
      Message.error(message || data)
      return false
    }
  } catch (errors) {
    console.log('校验失败:', errors)
    return false
  }
}

const resetForm = () => {
  if (taskFormRef.value) {
    taskFormRef.value.clearValidate()
    taskForm.value = cloneDeep(DEFAULT_TASK_FORM)
  }
}
const handleBeforeClose = () => {
  resetForm()
}

const loadList = async () => {
  try {
    tableLoading.value = true
    const { code, data } = await apiHome.getTaskInfoPageListAPI({
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    })
    if (code === 200) {
      tableLoading.value = false
      data.list.forEach((item) => {
        item.taskStatus = item.taskStatus !== '0'
        item.healthScore = item.healthScore?.toFixed(2)
      })
      taskPageData.value = data.list
      pagination.value.total = Number(data.total)
    }
  } catch (e) {
    console.log(e)
  } finally {
    tableLoading.value = false
  }
}
loadList()

const handlePageChange = (page) => {
  pagination.value.pageNum = page
  loadList()
}

const handlePageSizeChange = (size) => {
  pagination.value.pageSize = size
  loadList()
}

const detailVisible = ref(false)
const cronVisible = ref(false)
const cronObj = reactive({
  cron: '',
  userSetting: null
})
const setCron = () => {
  cronVisible.value = true
}
const changeCron = (cron) => {
  if (cron) {
    taskForm.value.cronExpression = cron[0]
  }
}

const closeCron = () => {
  cronVisible.value = false
}
const systemSelectLoading = ref(false)
const indexSystemOptions = ref([])
const getSystemSelectList = async () => {
  try {
    systemSelectLoading.value = true
    const { code, data } = await apiHome.getPortraitDataList('1', 1, 999)
    if (code === 200) {
      indexSystemOptions.value = data.list
    }
  } catch (e) {
    console.log(e)
  } finally {
    systemSelectLoading.value = false
  }
}

const handleDetail = async (record) => {
  try {
    const { code: listCode, data: listData } = await apiHome.getPortraitDataList('1', 1, 999)
    tableLoading.value = true
    const { code, data, message } = await apiHome.getDetailInfoAPI(record.id)
    if (code === 200) {
      descData.value.forEach((item) => {
        if (data[item.code]) {
          if (
            item.code === 'startTime' ||
            item.code === 'endTime' ||
            item.code === 'createTime' ||
            item.code === 'updateTime'
          ) {
            item.value = dayjs(data[item.code]).format('YYYY-MM-DD HH:mm:ss')
          } else if (item.code === 'taskStatus') {
            item.value = data[item.code] === '0' ? '停止' : '启动'
          } else if (item.code === 'indexSystemId') {
            item.value = listData.list.find((subItem) => subItem.id === data[item.code])?.nodeName || ''
          } else {
            item.value = data[item.code] ?? ''
          }
        } else {
          item.value = ''
        }
      })
      tableLoading.value = false
      detailVisible.value = true
    } else {
      Message.error(message)
    }
  } catch (e) {
    console.log(e)
  } finally {
    tableLoading.value = false
  }
}
const handleEdit = async (record) => {
  tableLoading.value = true
  await getSystemSelectList()
  try {
    dialogType.value = 'edit'
    const { code, data, message } = await apiHome.getDetailInfoAPI(record.id)
    if (code === 200) {
      taskForm.value = { ...data }
      taskForm.value.dateRange = [data.startTime, data.endTime]
      visible.value = true
      tableLoading.value = false
    } else {
      Message.error(message)
    }
  } catch (e) {
    console.log(e)
  } finally {
    tableLoading.value = false
  }
}
const handleDelete = (record) => {
  Modal.confirm({
    title: '提示',
    content: `确定要删除【${record.taskName}】这个任务吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        const { code, message } = await apiHome.deleteTaskAPI([record.id])
        if (code === 200) {
          Message.success('删除成功')
        } else {
          Message.error(message || '删除失败')
        }
      } catch (e) {
        console.log(e)
      } finally {
        await loadList()
      }
    }
  })
}
const dateRangeChange = (date) => {
  if (date) {
    taskForm.value.startTime = date[0]
    taskForm.value.endTime = date[1]
  } else {
    taskForm.value.startTime = ''
    taskForm.value.endTime = ''
  }
}
const handleStartOrStop = async (val, record) => {
  try {
    tableLoading.value = true
    const { code, data, message } = await apiHome.startOrStopTaskAPI(record.id)
    if (code === 200) {
      Message.success(message || data)
    } else {
      Message.error(message || data)
    }
  } catch (e) {
    console.log(e)
  } finally {
    await loadList()
  }

  console.log(val)
  console.log(record)
}
</script>

<template>
  <div class="page-task-management">
    <div class="table-card">
      <div class="table-card-header">
        <div class="table-card-header-right">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <icon-plus />
            </template>
            新建
          </a-button>
        </div>
      </div>
      <a-table
        :columns="columns"
        :data="taskPageData"
        :pagination="false"
        :scroll="scroll"
        :scrollbar="false"
        :loading="tableLoading"
      >
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #action="{ record }">
          <a-button status="success" size="mini" type="text" @click="handleDetail(record)">
            <template #icon>
              <icon-file />
            </template>
            详情
          </a-button>
          <a-button size="mini" type="text" @click="handleEdit(record)">
            <template #icon>
              <IconEdit />
            </template>
            修改
          </a-button>
          <a-button status="danger" size="mini" type="text" @click="handleDelete(record)">
            <template #icon>
              <IconDelete />
            </template>
            删除
          </a-button>
          <a-switch type="round" v-model="record.taskStatus" @change="(val) => handleStartOrStop(val, record)">
            <template #checked>停止服务</template>
            <template #unchecked>启动服务</template>
          </a-switch>
        </template>
      </a-table>
      <div class="table-card-footer">
        <a-pagination
          :total="pagination.total"
          :current="pagination.page"
          :page-size="pagination.pageSize"
          show-total
          show-jumper
          show-page-size
          @change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />
      </div>
    </div>
    <a-modal
      v-model:visible="visible"
      :title="dialogTitle"
      :on-before-ok="handleSubmit"
      :onBeforeClose="handleBeforeClose"
      unmountOnClose
    >
      <a-form :model="taskForm" ref="taskFormRef" auto-label-width :rules="taskFormRules">
        <a-form-item field="taskName" label="任务名称" :validate-trigger="['change', 'input']">
          <a-input v-model="taskForm.taskName" placeholder="任务名称" allow-clear />
        </a-form-item>
        <a-form-item field="indexSystemId" label="评估系统">
          <a-select
            v-model="taskForm.indexSystemId"
            placeholder="请选择评估系统"
            allow-clear
            :loading="systemSelectLoading"
          >
            <a-option :value="item.id" v-for="item in indexSystemOptions" :key="item.id">{{ item.nodeName }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="dateRange" label="查询数据时间段">
          <a-range-picker v-model="taskForm.dateRange" showTime allow-clear @change="dateRangeChange" />
        </a-form-item>
        <a-form-item field="cronExpression" label="cron表达式">
          <a-input v-model="taskForm.cronExpression" placeholder="cron表达式" allow-clear />
          <a-button type="primary" style="margin-left: 16px" @click="setCron">设置</a-button>
        </a-form-item>
        <a-form-item field="remark" label="备注">
          <a-textarea v-model="taskForm.remark" placeholder="备注" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:visible="detailVisible" title="任务详情" ok-text="关闭" hide-cancel>
      <a-descriptions :data="descData" bordered size="large" :column="1" />
    </a-modal>
    <a-modal v-model:visible="cronVisible" title="设置定时器" width="650px" :footer="false">
      <vue3-cron :cron-value="cronObj" @change-cron="changeCron" @close="closeCron" />
    </a-modal>
  </div>
</template>

<style scoped lang="less">
.page-task-management {
  height: 100%;

  .table-card {
    height: 100%;

    &-header {
      margin-bottom: 16px;

      &-right {
        text-align: right;
      }
    }

    &-footer {
      margin-top: 16px;
      margin-right: 16px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
